package com.ningxun.pagent.flow.listener;

import com.ningxun.pagent.common.core.domain.entity.SysUser;
import com.ningxun.pagent.common.utils.StringUtils;
import com.ningxun.pagent.flow.service.impl.ChartExtServiceImpl;
import com.ningxun.pagent.system.service.ISysUserService;
import org.dromara.warm.flow.core.FlowEngine;
import org.dromara.warm.flow.core.dto.DefJson;
import org.dromara.warm.flow.core.dto.NodeJson;
import org.dromara.warm.flow.core.listener.GlobalListener;
import org.dromara.warm.flow.core.listener.ListenerVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 全局监听器: 整个系统只有一个，任务开始、分派、完成和创建时期执行
 *
 * @author warm
 * @since 2024/11/17
 */
@Component
public class CustomGlobalListener implements GlobalListener {


        @Autowired
        private ISysUserService userService;
        private static final Logger logger = LoggerFactory.getLogger(ChartExtServiceImpl.class);

        /**
         * 分派监听器，动态修改代办任务信息
         * @param listenerVariable  监听器变量
         */
        @Override
        public void assignment(ListenerVariable listenerVariable) {
            logger.info("全局分派监听器开始执行......");

            String defJsonStr = listenerVariable.getInstance().getDefJson();
            if (StringUtils.isNotBlank(defJsonStr)) {
                DefJson defJson = FlowEngine.jsonConvert.strToBean(defJsonStr, DefJson.class);
                for (NodeJson nodeJson : defJson.getNodeList()) {
                    if (nodeJson.getNodeCode().equals(listenerVariable.getNode().getNodeCode())) {
                        Long userId = Long.valueOf(listenerVariable.getFlowParams().getHandler());

                        SysUser sysUser = userService.selectUserById(userId);
                        if (sysUser != null && StringUtils.isNotEmpty(sysUser.getNickName())) {
                            nodeJson.getExtMap().put("办理人", sysUser.getNickName());
                        }
                        // 年月日时分秒
                        nodeJson.getExtMap().put("办理时间", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    }
                }
                listenerVariable.getInstance().setDefJson(FlowEngine.jsonConvert.objToStr(defJson));
            }

            logger.info("全局分派监听器执行结束......");
        }
    }


